import Vue from 'vue'
import VueRouter from 'vue-router'
import Admin from '_views/Admin'
import store from '../store'
import { isLogin } from '_utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: '首页',
    component: Admin,
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        name: '仪表盘',
        meta: {
          roles: ['a', 'b', 'c']
        },
        component: () => import('_views/DashBoard')
      },
      {
        path: '/cateLists',
        name: '分类管理',
        meta: {
          roles: ['a', 'b', 'c']
        },
        component: () => import('_views/CateLists')
      },
      {
        path: '/itemLists',
        name: '商品管理',
        meta: {
          roles: ['a', 'b', 'c']
        },
        component: () => import('_views/ItemLists')
      },
      {
        path: '/itemAdd',
        name: '增加商品',
        meta: {
          roles: ['a', 'b', 'c']
        },
        component: () => import('_views/ItemAdd')
      },
      {
        path: '/itemUpdate',
        name: '修改商品',
        meta: {
          roles: ['a', 'b', 'c']
        },
        component: () => import('_views/ItemUpdate')
      },
      {
        path: '/setting',
        name: '设置',
        meta: {
          roles: ['b', 'c']
        },
        component: () => import('_views/Setting')
      }
    ]
  },
  {
    path: '/login',
    name: '登录',
    meta: {
      roles: '*'
    },
    component: () => import('_views/Login')
  },
  {
    path: '/noAuth',
    name: '/noAuth',
    meta: {
      roles: '*'
    },
    component: () => import('_views/NoAuth')
  },
  {
    path: '*',
    name: 'NotFound',
    meta: {
      roles: '*'
    },
    component: () => import('_views/NotFound')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 登录路由鉴权

router.beforeEach((to, from, next) => {
  const role = localStorage.getItem('role') || ''
  if (to.path !== '/login') {
    if (isLogin()) {
      /*
        路由角色鉴权
      */
      // 判断 roles是否是*
      if (to.meta.roles === '*') {
        next()
      } else {
        if (to.meta.roles.includes(role)) {
          // 有权限可以访问
          next()
        } else {
          // 没有权限 去 没有权限路由
          next('/noAuth')
        }
      }
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
// 路由后置守卫 实现 全局 navTabs 添加
router.afterEach((to, from) => {
  const noTabPath = ['/login', '/dashBoard', '/noAuth']
  if (!noTabPath.includes(to)) {
    store.commit('base/ADD_NAV_TAB', {
      name: to.name,
      path: to.path
    })
  }
})

export default router
